/*
 * @Author: MarsLay 331412466@qq.com
 * @Date: 2023-06-20 14:29:06
 * @LastEditors: MarsLay 331412466@qq.com
 * @LastEditTime: 2023-12-05 14:37:16
 * @FilePath: \nanhu-manage-pc\src\api\service.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from "axios";
import router from "../router";
import store from "../store/index";
import { Message } from "element-ui";

axios.interceptors.request.use(
  (config) => {
    const userinfo = JSON.parse(localStorage.getItem("userinfo"));
    config.method === "post" ? (config.data = JSON.stringify(config.data)) : (config.params = { ...config.params });
    config.headers["Content-Type"] = "application/json";
    config.headers["Authorization"] = userinfo ? "bearer " + userinfo.token : "bearer ";
    config.headers["Platformid"] = 1;
    return config;
  },
  (err) => {
    console.error("axios request 请求出错：", err);
    return Promise.error(err);
  }
);

axios.interceptors.response.use(
  (response) => {
    if (response && response.data) {
      let data = response.data || {};
      if (data && data["code"] != 200) {
        store.state.loading = false;
        Message({
          type: "error",
          message: data.message,
        });
      }
    }
    return response;
  },
  (err) => {
    //console.error("axios response 请求出错：", err);
    Message.error("系统错误，请重试！");
    store.state.loading = false;
    setTimeout(() => {
      router.push("/");
      const remember = JSON.parse(localStorage.getItem("remember"));
      localStorage.clear();
      remember?.length > 0 && localStorage.setItem("remember", JSON.stringify(remember));
    }, 1000);
    return Promise.reject(err);
  }
);

export default axios;
